package com.hirstlogics.boxarrow.model;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import com.hirstlogics.boxarrow.xml.Persist;

public class Description implements Persist {
	String desc = null;

	List<Description> subDesc = null;

	public Description(String text) {
		desc = text;
	}
	
	@Override
	public boolean equals(Object obj) {
		boolean isEqual=false;
		if (obj==null) return false;
		if (!this.getClass().isInstance(obj)) return false;
		Description d1= (Description) obj;
		if ((desc==null) && (d1.desc==null)) return true;
		isEqual = desc.equals(d1.desc);
		return isEqual;
	}

	@Override
	public String toString() {
		StringBuffer result = new StringBuffer();
		if (desc != null)
			result.append(desc);
		if (subDesc != null)
			for (int idx = 0; idx < subDesc.size(); idx++) {
				result.append(subDesc.get(idx).toString());
			}
		return result.toString();
	}

	public String toXML() {
		StringWriter result = new StringWriter();
		XMLOutputFactory xmlof = XMLOutputFactory.newInstance();
		try {
			XMLStreamWriter writer = xmlof.createXMLStreamWriter(result);
			render(writer);
		} catch (XMLStreamException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result.toString();
	}

	public void render(XMLStreamWriter writer) throws XMLStreamException {
		writer.writeStartElement("ba", DESCRIPTION, BOXARROW);
		renderDiv(this, writer);
		writer.writeEndElement();
	}

	private static void renderDiv(Description desc, XMLStreamWriter writer) throws XMLStreamException {
		writer.writeStartElement("div");
		writer.writeCharacters(desc.desc);
		if (desc.hasSubDesc()) {
			for(int idx=0;idx<desc.subDesc.size();idx++) {
				renderDiv(desc.subDesc.get(idx),writer);
			}
		}
		writer.writeEndElement();
	}

	public void setDesc(String text) {
		desc = text;
	}

	public void clear() {
		desc = null;
		subDesc = null;
	}

	public void addDesc(String text) {
		if (subDesc == null)
			subDesc = new ArrayList<Description>();
		subDesc.add(new Description(text));
	}
	
	public void addDesc(Description desc) {
		if (subDesc == null)
			subDesc = new ArrayList<Description>();
		subDesc.add(desc);
		
	}

	public boolean hasSubDesc() {
		return subDesc != null && subDesc.size() > 0;
	}


}
